<template>
  <a-tabs :activeKey="activeKey" type="editable-card" hideAdd @change="setActiveKey" @edit="onEdit">
    <a-tab-pane
      v-for="pane in panes"
      :key="pane.key"
      :tab="pane.title"
      :closable="closable"
    >
    </a-tab-pane>
  </a-tabs>
</template>
<script>
import { toRefs, computed, defineComponent } from 'vue'

export default defineComponent({
  name: 'DynamicTabs',
  props: {
    panes: {
      type: Array,
      default: () => [
        {
          title: '默认',
          key: '1',
          closable: false
        }
      ]
    },
    activeKey: {
      type: String,
      default: ''
    }
  },
  emits: ['update:activeKey', 'remove'],
  setup (props, context) {
    const { panes } = toRefs(props)

    const setActiveKey = selfKey => {
      context.emit('update:activeKey', selfKey)
    }

    const closable = computed(() => {
      return panes.value.length > 1
    })

    const add = () => {
      console.log('add tab')
    }

    const remove = targetKey => {
      context.emit('remove', targetKey)
    }

    const onEdit = (targetKey, action) => {
      if (action === 'add') {
        add()
      } else {
        remove(targetKey)
      }
    }

    return {
      closable,
      setActiveKey,
      onEdit
    }
  }
})
</script>
